<?php
/**
 * 文件操作
 * User: dxk
 * Date: 2020/07/17
 */
namespace App\Library\Service;

use App\Service\Core\Merchant\MerchantService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class FileService
{
    /**
     * 商家端生成加密下载字符串
     * @param $file_path
     * @param int $merchant_id
     * @param int $operate_id
     * @return string
     */
    public static function encryptDownload($file_path, $merchant_id = 0, $operate_id = 0)
    {
        $info = ['f' => $file_path, 's' => $merchant_id, 'u' => $operate_id];
        $file_encrypt = Crypt::encrypt(json_encode($info));
        return easy_url('merchant/file/download', ['file_encrypt' => $file_encrypt]);
    }

    /**
     * 文件下载解密
     * @param Request $request
     * @param int $merchant_id
     * @param int $operate_id
     * @return array
     */
    public static function decryptDownload(Request $request, $merchant_id = 0, $operate_id = 0)
    {
        $file_encrypt = trim($request->input('file_encrypt'));
        if (empty($file_encrypt)) {
            return alert_info(1, '非法的文件下载请求');
        }
        $file_info = json_decode(Crypt::decrypt($file_encrypt), true);
        if (!is_array($file_info) || empty($file_info)) {
            return alert_info(1, '非法的文件下载请求');
        }
        $s = trim($file_info['s']);
        $u = trim($file_info['u']);
        $file_path = $file_info['f'];
        if ($merchant_id != $s || $operate_id != $u) {
            return alert_info(1, '您无权限下载此文件');
        }
        if (empty($file_path)) {
            return alert_info(1, '文件不存在');
        }
        $download_file_path = easy_attached_path($file_path);
        if (!is_file($download_file_path)) {
            return alert_info(1, '文件已经不存在');
        }
        return alert_info(0, 'OK', ['file_path' => $download_file_path]);
    }

    /**
     * @param $file_info
     * @return string
     */
    public function encryptDownloadFile($file_info)
    {
        $info = [
            'file_id' => $file_info['file_id'],
            'file_path' => $file_info['file_path'],
            'merchant_id' => $file_info['merchant_id'],
            'operate_id' => $file_info['created_operate_id'],
            'timestamp' => time(),
        ];
        $file_encrypt = Crypt::encrypt(json_encode($info));
        if ($file_info['operate_type'] == 1) {
            $url = 'http://attached' . $server_id . '.' . env('CUSTOM_MAIN_DOMAIN') . '/down_file?file_encrypt=' . $file_encrypt;
        } else {
            $url = easy_url('down_file', ['file_encrypt' => $file_encrypt]);
        }
        return $url;
    }
}
